package config

import (
	"fmt"
	"time"
)

// MySQL mysql connection configs
type MySQL struct {
	Host         string `toml:"host"`
	Port         string `toml:"port"`
	Username     string `toml:"username"`
	Password     string `toml:"password"`
	Database     string `toml:"database"`
	MaxIdleConns int    `toml:"max_idle_conns"`
	MaxOpenConns int    `toml:"max_open_conns"`
	MaxLifeTime  int64  `toml:"max_life_time"`
}

// GetURL return MySQL address
func (cfg *MySQL) GetURL() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
}

// GetMaxIdleConns return MySQL max idle connections
func (cfg *MySQL) GetMaxIdleConns() int {
	if cfg.MaxIdleConns > 0 {
		return cfg.MaxIdleConns
	}
	return 10
}

// GetMaxOpenConns return MySQL max open connections
func (cfg *MySQL) GetMaxOpenConns() int {
	if cfg.MaxOpenConns > 0 {
		return cfg.MaxOpenConns
	}
	return 10
}

// GetMaxLifeTime return MySQL max life time, unit: s
func (cfg *MySQL) GetMaxLifeTime() time.Duration {
	if cfg.MaxLifeTime > 0 {
		return time.Duration(cfg.MaxLifeTime) * time.Second
	}
	return 1800 * time.Second
}
